/**
 * 文件名    ： NovelCrawController.java
 * 版权       : XX科技有限公司。
 * 描述       : <描述>
 * 修改时间：2018年11月14日
 * 修改内容：<修改内容>
 */
package com.example.demo.application.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.example.demo.application.common.MyConstantsRespone;
import com.example.demo.application.common.base.ResultMsg;
import com.example.demo.application.common.base.ResultMsgPage;
import com.example.demo.application.crawutil.novel.NovelCrawTextThread;
import com.example.demo.application.model.NovelCrawEntity;
import com.example.demo.application.service.INovelService;
import com.example.demo.application.threadutil.MyThreadPoolExecutor;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api(description = "小说管理接口")
@RestController
@EnableAutoConfiguration
@RequestMapping(path = "/novelcraw")
public class NovelCrawController {

	protected final Logger log = LoggerFactory.getLogger(NovelCrawController.class);

	@Resource(name = "novelService")
	private INovelService novelService;

	/**
	 * <一句话功能简述> 下载小说文件 <功能详细描述>
	 * 
	 * @param form
	 * @throws Exception
	 * @see [类、类#方法、类#成员]
	 */
	@ApiOperation(value = "下载", notes = "下载")
	@RequestMapping(path = "/toload", method = RequestMethod.POST)
	@ResponseBody
	public ResultMsg toload(@RequestBody NovelCrawEntity form) throws Exception {
		ResultMsg modelMap = new ResultMsg();
		if (null == form || null == form.getIds()) {
			form = new NovelCrawEntity();
			List<Integer> ids = new ArrayList<>();
			ids.add(1);
			form.setIds(ids);
		}
		form.setPageSize(1000);
		List<NovelCrawEntity> novels = novelService.findByParams(form);
		for (NovelCrawEntity novel : novels) {
			// 未下载或者失败
			if (checkEmpty(novel) || (!"1".equals(novel.getStatus()) && !"-1".equals(novel.getStatus()))) {
				continue;
			}
			// 准备下载
			novel.setStatus("2");
			novel.setLastTime(new Date());
			novelService.update(novel);
			NovelCrawTextThread crawTextThread = new NovelCrawTextThread(novel, novelService);
			/// 分配到哪个 线程池取下载
			MyThreadPoolExecutor.getInstance().execute(crawTextThread, novel.getThreadPoolName());
		}
		modelMap.setCode(MyConstantsRespone.success);
		return modelMap;
	}

	@ApiOperation(value = "查询", notes = "查询")
	@RequestMapping(path = "/getNovels", method = RequestMethod.POST)
	@ResponseBody
	public ResultMsgPage getNovels(@RequestBody NovelCrawEntity form) throws Exception {
		ResultMsgPage modelMap = new ResultMsgPage();
		List<NovelCrawEntity> novels = new ArrayList<>();
		if (null != form) {
			int index = form.getIndex();
			if (index > 0) {
				form.setIndex(index - 1);
			}
			novels = novelService.findByParams(form);
			modelMap.setTotalPage(form.getTotlePage());//put("totalPage", form.getTotlePage());
			modelMap.setPageSize(form.getPageSize());//put("pageSize", form.getPageSize());
			modelMap.setForm(form);//put("form", form);
			modelMap.setCode(MyConstantsRespone.success);//put("code", MyConstantsRespone.success);
			form.setIndex(index);
		} else {
			modelMap.setCode(MyConstantsRespone.fail);
		}
		modelMap.setData(novels);//put("data", novels);
		return modelMap;

	}

	@ApiOperation(value = "更新", notes = "更新")
	@RequestMapping(path = "/update", method = RequestMethod.POST)
	@ResponseBody
	public ResultMsg update(@RequestBody NovelCrawEntity form) throws Exception {
		ResultMsg modelMap = new ResultMsg();
		if (null != form) {
			form.setLastTime(new Date());
			if (form.getId() > 0) {
				novelService.update(form);
			} else {
				form.setCreateTime(new Date());
				novelService.insert(form);
			}
			modelMap.setCode(MyConstantsRespone.success);
		} else {
			modelMap.setCode(MyConstantsRespone.fail);
		}
		return modelMap;
	}

	@ApiOperation(value = "查看", notes = "查看")
	@RequestMapping(path = "/findById/{id}", method = RequestMethod.GET)
	@ResponseBody
	public ResultMsg findById(@PathVariable String id) throws Exception {
		ResultMsg modelMap = new ResultMsg();
		NovelCrawEntity form = new NovelCrawEntity();
		form.setId(Integer.parseInt(id));
		NovelCrawEntity entity = novelService.findById(form);
		modelMap.setData(entity);
		modelMap.setCode(MyConstantsRespone.success);
		return modelMap;
	}

	/**
	 * <一句话功能简述> 必传参数 <功能详细描述>
	 * 
	 * @param novel
	 * @return
	 * @see [类、类#方法、类#成员]
	 */
	private boolean checkEmpty(NovelCrawEntity novel) {
		if (StringUtils.isEmpty(novel.getDestUrl())) {
			return true;
		}
		if (StringUtils.isEmpty(novel.getRule())) {
			return true;
		}
		if (StringUtils.isEmpty(novel.getUserAgent())) {
			return true;
		}
		if (StringUtils.isEmpty(novel.getTitle())) {
			return true;
		}
		if (StringUtils.isEmpty(novel.getUrlNodeTemplet())) {
			return true;
		}
		if (StringUtils.isEmpty(novel.getTitleLab())) {
			return true;
		}
		if (StringUtils.isEmpty(novel.getContentLab())) {
			return true;
		}
		if (StringUtils.isEmpty(novel.getFilePath())) {
			return true;
		}
		return false;
	}
}
